/* ************************************************************************
 *	异步请求
 *************************************************************************/
import {assign} from "../core";

/**
 * ajax -依赖Jquery
 * @param {*} options
 */
function request(options) {
	options = $.extend({}, request.defaults, options);
	delete options.success;
	delete options.error;

	const chain = [].concat(request.interceptors.request, [{
		fulfilled: () => {
			return $.ajax(options).then((res, _, XMLHttpRequest) => {
				XMLHttpRequest.data = res;
				XMLHttpRequest.config = options;
				return $.Deferred().resolve(XMLHttpRequest);
			}, (XMLHttpRequest) => {
				XMLHttpRequest.config = options;
				return $.Deferred().reject(XMLHttpRequest);
			});
		},
		rejected: null
	}], request.interceptors.response);

	let promise = new $.Deferred();
	promise.resolve(options);
	chain.forEach(interceptor => promise = promise.then(interceptor.fulfilled, interceptor.rejected));

	return promise;
}

/**
 * 默认配置
 * @type {*}
 */
request.defaults = {
	timeout: 15 * 1000,
	xhrFields: {
		withCredentials: true
	},
	dataType: "json",
};

/**
 * 拦截器
 * @type {{request: [], response: []}}
 */
request.interceptors = {
	request: [],
	response: []
};

/**
 * 添加请求拦截器
 * @param {function} [fulfilled]
 * @param {function} [rejected]
 * @return {number}
 */
request.addRequestInterceptor = function(fulfilled, rejected) {
	return request.interceptors.request.push({
		fulfilled: fulfilled,
		rejected: rejected
	}) - 1;
};

/**
 * 移除拦截器
 * @param {number} number
 */
request.removeRequestInterceptor = function(number) {
	request.interceptors.request.splice(number, 0);
};

/**
 * 添加服务器结果拦截器
 * @param {function} [fulfilled]
 * @param {function} [rejected]
 * @return {number}
 */
request.addResponseInterceptor = function(fulfilled, rejected) {
	return request.interceptors.response.push({
		fulfilled: fulfilled,
		rejected: rejected
	}) - 1;
};

/**
 * 移除拦截器
 * @param {number} number
 */
request.removeResponseInterceptor = function(number) {
	request.interceptors.response.splice(number, 0);
};

//注册快捷方法
['get', 'post', 'put', 'delete'].forEach(method => {
	request[method] = function(url, data, options = {}) {
		return request(assign(options, {
			url: url,
			method: method,
			data: data,
		}));
	};
});

export default request;
